package com.ch.playandroid.webView

import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.viewModels
import com.ch.common.base.fragment.BaseFragment
import com.ch.playandroid.R
import com.ch.playandroid.databinding.AppFragmentWebViewBinding

class WebFragment : BaseFragment<WebViewModel, AppFragmentWebViewBinding>() {

    override fun bindViewModel() {
        mBinding.viewModel = viewModel
    }

    override val viewModel: WebViewModel by viewModels()

    override fun getLayoutResID(): Int {
        return R.layout.app_fragment_web_view
    }

    override fun initView() {
        val webSettings = mBinding.wv.settings
        webSettings.domStorageEnabled = true
        webSettings.loadWithOverviewMode = true
        webSettings.useWideViewPort = true
        webSettings.javaScriptEnabled = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        mBinding.wv.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        mBinding.wv.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    mBinding.webProgressBar.visibility = View.GONE
                } else {
                    if (View.INVISIBLE == mBinding.webProgressBar.visibility) {
                        mBinding.webProgressBar.visibility = View.VISIBLE
                    }
                    mBinding.webProgressBar.progress = newProgress
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        mBinding.wv.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                return false
            }
        }
        // 加载页面
        if(mContext is PlayWebViewActivity) {
            mBinding.wv.loadUrl((mContext as PlayWebViewActivity).getUrl)
        }

    }

    override fun onResume() {
        super.onResume()
        mBinding.wv.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.wv.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.wv.clearCache(true)
        mBinding.wv.removeAllViews()
        mBinding.wv.destroy()
    }

    override fun initObserve() {

    }

    companion object {
        fun actionCrate(): WebFragment {
            return WebFragment()
        }
    }
}